package com.sherlocky.exception;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import com.sherlocky.util.WebMessage;

public class GlobalExceptionResolver implements HandlerExceptionResolver{
	private Log logger = LogFactory.getLog(getClass());
	
	public ModelAndView resolveException(HttpServletRequest request,
			HttpServletResponse response, Object handler, Exception ex) {
		if(ex instanceof ShowMessageException) {
			ShowMessageException e = (ShowMessageException)ex;
			if(e.isAjax()){
				try{
					WebMessage.sendMessage(response, e.getMessage());
					return null;
				}catch (Exception exception) {
					WebMessage.setErrorMessage(request, "发送信息失败，失败原因：" + exception.getMessage());
				}
			}else{
				WebMessage.setErrorMessage(request, e.getMessage());
				return new ModelAndView("/error/message");
			}
		}
		ex.printStackTrace();
		logger.error("统一处理Spring Controller异常", ex);
		if(ex instanceof NullPointerException) {
			WebMessage.setErrorMessage(request, "空指针异常");
		}else{
			WebMessage.setErrorMessage(request, ex.getMessage());
		}
		return new ModelAndView("/error/message");
	}
}